<?php
class VerificationController extends Yaf\Controller_Abstract{

    public function init(){
        Yaf\Dispatcher::getInstance()->disableView();
    }

    public function seekPassAction(){
        $name = $_POST['username'];
//        查找邮箱
        $email = UsersModel::where('username','=',$name)->select('email')->get();

        if (count($email)>0){
            $emails = json_decode($email,true);
            $findEmail = $emails[0]['email'];
//            生成验证码
            $Verification = rand(1000,9999);
//            将验证码和邮箱存入数据库
//            $forgets = new ForgetPasswordModel();
            $code=["id"=>null,
                "email"=>$findEmail,
                "validcode"=>$Verification];
            $resu=ForgetPasswordModel::insert($code);
            if ($resu>0){
            $content =  "邮箱为:".$findEmail."：<br/>的用户您好。<br/>当前您正在进行找回密码的操作，验证码为:<br/>
                     ".$Verification."<br/> 请及时使用，如非本人操作，请忽略";
            $sendMails = new MailsModel();
            $results = $sendMails->sendMail($findEmail,'忘记密码',$content);

            if ($results){
                $msg = ".验证码已发送，请及时验收";
                $flag=true;

            }else{
                $msg = "$results.验证码发送失败，请重新请求";
                $flag=false;
            }
         }
        }
        $arr=array("msg"=>$msg,"flag"=>$flag);
        echo json_encode($arr,JSON_UNESCAPED_UNICODE );
    }

    public function updatePassAction(){
        $code = $_POST['vcode'];
        $newPass = $_POST['pword'];
        //拼接salt字段然后进行md5加密
        $salt = rand(10000,99999);
        $mdPass = md5(''.$newPass.$salt);
//        通过验证码找到邮箱
        $Vemail = ForgetPasswordModel::where('validcode','=',$code)->select('email')->get();
//        判断邮箱
        if (count($Vemail)>0){
            $emails = json_decode($Vemail,true);
            $VsEmail = $emails[0]['email'];
//      通过邮箱查找到ID
        $id = UsersModel::where('email','=',$VsEmail)->select('id')->get();
//        判断id
            if (count($id)>0){
                $ids = json_decode($id,true);
                $Vid = $ids[0]['id'];
//                通过ID直接更改密码和salt
                $sum = UsersModel::where('id','=',$Vid)->update(
                   ['password' => $mdPass,
                     'salt'=>$salt
                       ]
                );
                if ($sum =='1'){
                    $msg = "密码更改成功，跳转至登录界面......";
                    $flag=true;
                }else{
                    $msg = "密码修改失败";
                    $flag=false;
                }
            }
        }
        $arr=array("msg"=>$msg,"flag"=>$flag);
        echo json_encode($arr,JSON_UNESCAPED_UNICODE );
    }
}